package com.hulk.rpc.common;

import com.hulk.rpc.config.common.HostPort;
import io.netty.util.internal.InternalThreadLocalMap;

import java.lang.reflect.Method;

/**
 * @author xuxukang
 * @date 2019-04-28 22:55
 */
public class RemoteContext {

  private static final int CLIENT_ADDRESS_ATTACHMENT_INDEX = InternalThreadLocalMap
          .nextVariableIndex();
  private static final int SERVER_ADDRESS_ATTACHMENT_INDEX = InternalThreadLocalMap
          .nextVariableIndex();
  private static final int INVOKER_ATTACHMENT_INDEX = InternalThreadLocalMap.nextVariableIndex();
  private static final int SERVICE_METHOD_NAME_ATTACHMENT_INDEX = InternalThreadLocalMap
          .nextVariableIndex();

  private static final InternalThreadLocalMap THREAD_LOCAL_MAP = InternalThreadLocalMap.get();

  /**
   * 获取当前远程调用的客户端地址
   */
  public static HostPort getClientAddress() {
    return (HostPort) THREAD_LOCAL_MAP.indexedVariable(CLIENT_ADDRESS_ATTACHMENT_INDEX);
  }

  public static void setClientAddress(HostPort clientAddress) {
    THREAD_LOCAL_MAP.setIndexedVariable(CLIENT_ADDRESS_ATTACHMENT_INDEX, clientAddress);
  }

  /**
   * 获取当前远程调用的服务端地址
   */
  public static HostPort getServerAddress() {
    return (HostPort) THREAD_LOCAL_MAP.indexedVariable(SERVER_ADDRESS_ATTACHMENT_INDEX);
  }

  public static void setServerAddress(HostPort serverAddress) {
    THREAD_LOCAL_MAP.setIndexedVariable(SERVER_ADDRESS_ATTACHMENT_INDEX, serverAddress);
  }

  /**
   * 获取当前远程调用的接口方法, 可能为空
   */
  public static Method getRemoteMethod() {
    return (Method) THREAD_LOCAL_MAP.indexedVariable(INVOKER_ATTACHMENT_INDEX);
  }

  public static void setRemoteMethod(Method remoteMethod) {
    THREAD_LOCAL_MAP.setIndexedVariable(INVOKER_ATTACHMENT_INDEX, remoteMethod);
  }

  /**
   * 获取当前远程调用的服务名称, 可能为空
   */
  public static String getServiceMethodName() {
    return (String) THREAD_LOCAL_MAP.indexedVariable(SERVICE_METHOD_NAME_ATTACHMENT_INDEX);
  }

  public static void setServiceMethodName(String serviceMethodName) {
    THREAD_LOCAL_MAP.setIndexedVariable(SERVICE_METHOD_NAME_ATTACHMENT_INDEX, serviceMethodName);
  }


}
